package com.campus.food.controller;

import com.campus.food.model.entity.Address;
import com.campus.food.service.AddressService;
import com.campus.food.util.Result;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 地址控制器
 * 处理地址相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/addresses")
@Validated
public class AddressController {
    
    @Autowired
    private AddressService addressService;
    
    /**
     * 添加收货地址
     * POST /api/addresses
     */
    @PostMapping
    public Result<Address> addAddress(@Valid @RequestBody Address address) {

        try {
            Address savedAddress = addressService.addAddress(address);
            return Result.success("地址添加成功", savedAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加地址失败");
        }

    }
    
    /**
     * 根据ID获取地址信息
     * GET /api/addresses/{id}
     */
    @GetMapping("/{id}")
    public Result<Address> getAddressById(@PathVariable @NotNull Long id) {
        try {
            Address address = addressService.getAddressById(id);
            return Result.success(address);
        } catch (BusinessException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取地址信息失败");
        }
    }
    
    /**
     * 更新地址信息
     * PUT /api/addresses/{id}
     */
    @PutMapping("/{id}")
    public Result<String> updateAddress(@PathVariable @NotNull Long id,
                                      @RequestBody Address address) {

            address.setId(id);
            boolean success = addressService.updateAddress(address);
            if (success) {
                return Result.success("地址更新成功");
            } else {
                return Result.error("地址更新失败");
            }
    }
    
    /**
     * 删除地址
     * DELETE /api/addresses/{id}
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteAddress(@PathVariable @NotNull Long id,
                                      @RequestParam @NotNull Long userId) {
        try {
            boolean success = addressService.deleteAddress(id, userId);
            if (success) {
                return Result.success("地址删除成功");
            } else {
                return Result.error("地址删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除地址失败");
        }
    }
    
    /**
     * 获取用户地址列表
     * GET /api/addresses/user/{userId}
     */
    @GetMapping("/user/{userId}")
    public Result<List<Address>> getAddressByUserId(@PathVariable @NotNull Long userId) {
        try {
            List<Address> addresses = addressService.getAddressByUserId(userId);
            return Result.success(addresses);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取地址列表失败");
        }
    }
    
    /**
     * 获取用户默认地址
     * GET /api/addresses/default/{userId}
     */
    @GetMapping("/default/{userId}")
    public Result<Address> getDefaultAddress(@PathVariable @NotNull Long userId) {
        try {
            Address address = addressService.getDefaultAddress(userId);
            if (address == null) {
                return Result.notFound("用户没有设置默认地址");
            }
            return Result.success(address);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取默认地址失败");
        }
    }
    
    /**
     * 设置默认地址
     * PUT /api/addresses/{id}/default
     */
    @PutMapping("/{id}/default")
    public Result<String> setDefaultAddress(@PathVariable @NotNull Long id,
                                          @RequestParam @NotNull Long userId) {
        try {
            boolean success = addressService.setDefaultAddress(id, userId);
            if (success) {
                return Result.success("默认地址设置成功");
            } else {
                return Result.error("默认地址设置失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("设置默认地址失败");
        }
    }
    
    /**
     * 获取用户地址数量
     * GET /api/addresses/count/{userId}
     */
    @GetMapping("/count/{userId}")
    public Result<Long> getAddressCount(@PathVariable @NotNull Long userId) {
        try {
            long count = addressService.getAddressCount(userId);
            return Result.success(count);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取地址数量失败");
        }
    }
    
    /**
     * 搜索用户地址
     * GET /api/addresses/search/{userId}
     */
    @GetMapping("/search/{userId}")
    public Result<List<Address>> searchAddress(@PathVariable @NotNull Long userId,
                                             @RequestParam String keyword) {
        try {
            List<Address> addresses = addressService.searchAddress(userId, keyword);
            return Result.success(addresses);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("搜索地址失败");
        }
    }
    
    /**
     * 批量删除地址
     * DELETE /api/addresses/batch
     */
    @DeleteMapping("/batch")
    public Result<String> deleteAddressBatch(@RequestParam List<Long> ids,
                                           @RequestParam @NotNull Long userId) {
        try {
            boolean success = addressService.deleteAddressBatch(ids, userId);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("批量删除地址失败");
        }
    }
    
    /**
     * 获取所有地址列表（管理员专用）
     * GET /api/addresses/admin
     */
    @GetMapping("/admin")
    public Result<List<Address>> getAllAddresses(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int size,
                                               @RequestParam(required = false) Long userId) {
        try {
            List<Address> addresses = addressService.getAllAddresses(page, size, userId);
            return Result.success(addresses);
        } catch (Exception e) {
            return Result.error("获取地址列表失败");
        }
    }
} 